package view;

import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.concurrent.ExecutionException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.SwingWorker;

import model.Contact;
import model.Repertoire;

public class SwingFrame extends JFrame {
	Repertoire rep;
	JLabel firstname=new JLabel("First name: ");;
	JTextField firstext=new JTextField("name");
	JLabel lastname=new JLabel("Last name: ");
	JTextField lasttext=new JTextField("last name");
	JLabel address=new JLabel("Address: ");
	JTextField addresstext=new JTextField("address");
	JLabel compaddress=new JLabel("Company address: ");
	JTextField comptext=new JTextField("company address");
	JLabel persophone=new JLabel("Personal phone: ");
	JTextField persotext=new JTextField("0000000000");
	JLabel prophone=new JLabel("Professional phone: ");
	JTextField protext=new JTextField("0000000000");
	JLabel  persemail=new JLabel("Personal email: ");
	JTextField persemailtext=new JTextField("name@mail.com");
	JLabel  proemail=new JLabel("Professional email: ");
	JTextField proemailtext=new JTextField("name@mail.com");
	JLabel  homepage=new JLabel("Homepage: ");
	JTextField homepagetext=new JTextField("www.google.com");
	JFrame frame=new JFrame("Repertoire");
	JComboBox Listname=new JComboBox();
	JComboBox Listgroup=new JComboBox();
	JLabel  group=new JLabel("Group: ");
	JTextField grouptext=new JTextField("Group");
	JPanel pane=new JPanel(new GridBagLayout());
	JButton button=new JButton("Submit");
	JProgressBar progressBar=new JProgressBar();

	BufferedImage image= null;
	JLabel picLabel = new JLabel();
	JLabel statusLabel=new JLabel("current operation");

	JButton save=new JButton("Save");
	JButton load=new JButton("Load");
	JButton groupby=new JButton("Group by");
	JButton homepageLink=new JButton("Open homepage");
	JButton emailLink=new JButton("Open email");

	JButton alphabetize=new JButton("Alphabetize");

	final JButton delete=new JButton("Delete");
	final JButton show=new JButton("Show");

	final TextArea zone=new TextArea();
	final TextArea debugzone=new TextArea();
	GridBagConstraints c = new GridBagConstraints();
	private static int NBCONTACTS=1000;

 public SwingFrame(String title) {
  super(title);

  rep=new Repertoire(NBCONTACTS);
	String[]names=rep.getNames();
	Listname=new JComboBox(rep.getNames());
	Listgroup=new JComboBox(rep.getGroups());
	zone.setText(rep.showRepertoire());
	

	try {
		image=ImageIO.read(new File("./res/unknown.png"));
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	picLabel = new JLabel(new ImageIcon(image));


	c.fill = GridBagConstraints.HORIZONTAL;
	c.gridx = 0;
	c.gridy = 0;
	pane.add(firstname, c);
	c.gridx = 1;
	c.gridy = 0;	
	pane.add(firstext,c);
	c.gridx = 0;
	c.gridy = 1;
	pane.add(lastname,c);
	c.gridx = 1;
	c.gridy = 1;
	pane.add(lasttext,c);
	c.gridx = 0;
	c.gridy = 2;
	pane.add(address,c);
	c.gridx = 1;
	c.gridy = 2;
	pane.add(addresstext,c);
	c.gridx = 0;
	c.gridy = 3;
	pane.add(compaddress,c);
	c.gridx = 1;
	c.gridy = 3;
	pane.add(comptext,c);
	c.gridx = 0;
	c.gridy = 4;
	pane.add(persophone,c);
	c.gridx = 1;
	c.gridy = 4;
	pane.add(persotext,c);
	c.gridx = 0;
	c.gridy = 5;
	pane.add(prophone,c);
	c.gridx = 1;
	c.gridy = 5;
	pane.add(protext,c);
	c.gridx = 0;
	c.gridy = 6;
	pane.add(persemail,c);
	c.gridx = 1;
	c.gridy = 6;
	pane.add(persemailtext,c);
	c.gridx = 0;
	c.gridy = 7;
	pane.add(proemail,c);
	c.gridx = 1;
	c.gridy = 7;
	pane.add(proemailtext,c);
	c.gridx = 0;
	c.gridy = 8;
	pane.add(homepage,c);
	c.gridx = 1;
	c.gridy = 8;
	pane.add(homepagetext,c);
	c.gridx = 0;
	c.gridy = 9;
	pane.add(group,c);
	c.gridx = 1;
	c.gridy = 9;
	pane.add(grouptext,c);
	c.gridx = 0;
	c.gridy = 10;
	c.gridwidth = 2;
	pane.add(button);
	c.gridx = 3;
	c.gridy = 0;
	c.gridwidth = 4;
	c.gridheight = 6;
	pane.add(zone,c);
	c.gridx = 1;
	c.gridy = 13;
	c.gridwidth = 1;
	c.gridheight = 1;
	pane.add(picLabel,c);

	c.gridx = 1;
	c.gridy = 12;
	pane.add(Listname,c);
	c.gridx = 2;
	c.gridy = 12;
	pane.add(delete,c);
	c.gridx = 2;
	c.gridy = 1;
	pane.add(save,c);
	c.gridx = 2;
	c.gridy = 2;
	pane.add(load,c);
	c.gridx = 2;
	c.gridy = 3;
	pane.add(emailLink,c);
	c.gridx = 2;
	c.gridy = 4;
	pane.add(homepageLink,c);
	c.gridx = 3;
	c.gridy = 12;
	pane.add(show,c);
	c.gridx = 4;
	c.gridy = 12;
	pane.add(alphabetize,c);
	c.gridx = 5;
	c.gridy = 12;
	pane.add(groupby,c);
	c.gridx = 6;
	c.gridy = 12;
	pane.add(Listgroup,c);
	c.gridx = 3;
	c.gridy = 13;
	pane.add(statusLabel,c);
	c.gridx = 5;
	c.gridy = 13;
	pane.add(progressBar,c);
	frame.add(pane);


	button.addActionListener(
			new ActionListener(){
				public void actionPerformed(
						ActionEvent e){
					rep.addToRepertoire(
							firstext.getText(), 
							lasttext.getText(), 
							addresstext.getText(), 
							comptext.getText(), 
							Integer.parseInt(persotext.getText()), 
							Integer.parseInt(protext.getText()), 
							homepagetext.getText(), 
							proemailtext.getText(), 
							persemailtext.getText(),
							grouptext.getText(),
							null);
					zone.setText(rep.showRepertoire());
					Listname.addItem(lasttext.getText());
				}
			}
			);

	delete.addActionListener(
			new ActionListener(){
				public void actionPerformed(
						ActionEvent e){
					if(e.getSource()==delete){
						rep.deleteFromRepertoire(Listname.getSelectedItem().toString());
						Listname.removeItem(Listname.getSelectedItem());
						zone.setText(rep.showRepertoire());
					}
				}
			}
			);
	show.addActionListener(
			new ActionListener(){
				public void actionPerformed(
						ActionEvent e){
					if(e.getSource()==show){
						zone.setText(rep.getPerson(Listname.getSelectedItem().toString()));
					}
				}
			}
			);

	save.addActionListener(
			new ActionListener(){
				public void actionPerformed(
						ActionEvent e){
					startsave();
					
				}
			}
			);

	load.addActionListener(
			new ActionListener(){
				public void actionPerformed(
						ActionEvent e){
					progressBar.setMaximum(NBCONTACTS);
					progressBar.setMinimum(0);
					startload();
					debugzone.setText("laod done");
				}
			}
			);

	alphabetize.addActionListener(
			new ActionListener(){
				public void actionPerformed(
						ActionEvent e){
					rep.alphabetize();
					zone.setText(rep.showAlphaRepertoire());
					Listname=new JComboBox(rep.getNames());
					debugzone.setText("list alphabetized");
				}
			}
			);
	Listname.addActionListener(
			new ActionListener(){
				public void actionPerformed(
						ActionEvent e){
					Contact newcontact;
					newcontact=rep.findContact(Listname.getSelectedItem().toString());
					if(e.getSource()==Listname){
						firstext.setText(newcontact.getFirstname()); 
						lasttext.setText(newcontact.getLastname()); 
						addresstext.setText(newcontact.getAddress()); 
						comptext.setText(newcontact.getCompanyaddress()); 
						persotext.setText(Integer.toString(newcontact.getPersonalphone())); 
						protext.setText(Integer.toString(newcontact.getProfessionalphone())); 
						homepagetext.setText(newcontact.getHomepage()); 
						proemailtext.setText(newcontact.getProemail()); 
						persemailtext.setText(newcontact.getPeremail());
						grouptext.setText(newcontact.getGroup());
						try {
							picLabel.setIcon(new ImageIcon(ImageIO.read(new File(newcontact.getPhoto()))));
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				}
			}
			);

	homepageLink.addActionListener(
			new ActionListener(){
				public void actionPerformed(
						ActionEvent e){

					if(Desktop.isDesktopSupported()){
						try {
							Desktop.getDesktop().browse(new URI(homepagetext.getText()));
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (URISyntaxException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}

				}
			}
			);

	emailLink.addActionListener(
			new ActionListener(){
				public void actionPerformed(
						ActionEvent e){

					if(Desktop.isDesktopSupported()){
						try {
							Desktop.getDesktop().browse(new URI("mailto:"+persemailtext.getText()));
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (URISyntaxException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}

				}
			}
			);






	groupby.addActionListener(
			new ActionListener(){
				public void actionPerformed(
						ActionEvent e){
					zone.setText(" ");
					zone.setText(rep.showContactsGroup(Listgroup.getSelectedItem().toString()));
					debugzone.setText("list grouped");
				}
			}
			);

  frame.setLayout(new FlowLayout());
	frame.setResizable(false);
	frame.setSize(1100,500);
	frame.setVisible(true);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 
 public void setBar(int step){
		progressBar.setValue(step);
	}

 private void startload() {
	  Thread worker = new Thread() {
	   public void run() {
		   SwingWorker<Boolean, Integer> worker = new SwingWorker<Boolean, Integer>() {
			   @Override
			   protected Boolean doInBackground() throws Exception {
				   
				   rep.load();
				   for(int i=0;i<NBCONTACTS;i++){
					   progressBar.setValue(i);
				   }
				
			    return true;
			   }

			   protected void done() {
			    
			    boolean status;
			    try {
			     status = get();
			     statusLabel.setText("Loading completed? " + status);
			     zone.setText(rep.showRepertoire());
				Listname=new JComboBox(rep.getNames());
			    } catch (InterruptedException e) {
			    } catch (ExecutionException e) {
			    }
			   }

			   @Override    
			   protected void process(List<Integer> chunks) {
				  
			    
			   }
			   
			   
			  };
			  
			  worker.execute();
	    
	   }
	  };
	  
	  worker.start();
	 }
 
 private void startsave() {
	  Thread worker = new Thread() {
	   public void run() {
		   SwingWorker<Boolean, Integer> worker = new SwingWorker<Boolean, Integer>() {
			   @Override
			   protected Boolean doInBackground() throws Exception {
				   
				   rep.save();
				   for(int i=0;i<NBCONTACTS;i++){
					   progressBar.setValue(i);
				   }
				
			    return true;
			   }

			   protected void done() {
			    
			    boolean status;
			    try {
			     status = get();
			     zone.setText(rep.showRepertoire());
				Listname=new JComboBox(rep.getNames());
			     statusLabel.setText("Save completed? " + status);
			    } catch (InterruptedException e) {
			    } catch (ExecutionException e) {
			    }
			   }

			   @Override    
			   protected void process(List<Integer> chunks) {
				  
			    
			   }
			   
			   
			  };
			  
			  worker.execute();
	    
	   }
	  };
	  
	  worker.start();
	 }

 
 
}











